package r3.cluster.loadbalance;

import r3.common.R3Url;

import java.util.*;

/**
 * RandomLoadBalance
 * 随机选择组内一个可用服务
 * @author zhoufn
 * @create 2017-12-28 10:27
 **/
public class RandomLoadBalance implements LoadBalance{

    /**
     * @param worksSnapshot 内为当前可用服务的组列表，需要从每个组内选取一个可用服务；
     * @return 跨组可用服务列表
     * @throws Exception
     */
    @Override
    public List<R3Url> select(HashMap<String, HashMap<String, R3Url>> worksSnapshot) throws Exception {
        Random random = new Random();
        List<R3Url> selectors = new ArrayList<>();
        Set<String> workerSet = worksSnapshot.keySet();
        for(String worker : workerSet){
            HashMap<String,R3Url> urlMap = worksSnapshot.get(worker);
            if(urlMap.size() > 0){
                int index = random.nextInt(urlMap.size());
                R3Url url = urlMap.values().toArray(new R3Url[0])[index];
                selectors.add(url);
            }
        }
        return selectors;
    }
}
